const Product = require('../models/Product');
const Category = require('../models/Category');
const ProductCategory = require('../models/ProductCategory');

exports.create = async (req, res) => {
  try {
    const { name, price, image, logo, images, stock, description, category_id, user_category_id } = req.body;
    const product = await Product.create({
      name, price, image, logo,
      images: Array.isArray(images) ? JSON.stringify(images) : images,
      stock, description, category_id, user_category_id
    });
    res.json({ msg: '商品创建成功', product });
  } catch (err) {
    res.status(500).json({ msg: '商品创建失败', err });
  }
};

// 分页+搜索
exports.list = async (req, res) => {
  try {
    const page = parseInt(req.query.page, 10) || 1;
    const pageSize = parseInt(req.query.pageSize, 10) || 10;
    const keyword = req.query.keyword || '';
    const category_id = req.query.category_id;
    const user_category_id = req.query.user_category_id;
    const where = {};
    if (keyword) where.name = { [Product.sequelize.Op.like]: `%${keyword}%` };
    if (category_id) where.category_id = category_id;
    if (user_category_id) where.user_category_id = user_category_id;
    const { count, rows } = await Product.findAndCountAll({
      where,
      offset: (page - 1) * pageSize,
      limit: pageSize,
      order: [['created_at', 'DESC']],
      include: [
        { model: ProductCategory, as: 'product_category' },
        { model: Category, as: 'user_category' }
      ]
    });
    res.json({ total: count, list: rows });
  } catch (err) {
    res.status(500).json({ msg: '获取商品失败', err });
  }
};

// 新增：商品详情接口
exports.detail = async (req, res) => {
  try {
    const { id } = req.params;
    const product = await Product.findByPk(id);
    if (!product) return res.status(404).json({ msg: '商品不存在' });
    res.json(product);
  } catch (err) {
    res.status(500).json({ msg: '获取商品详情失败', err });
  }
};

exports.update = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, price, image, logo, images, stock, description, category_id, user_category_id } = req.body;
    const product = await Product.findByPk(id);
    if (!product) return res.status(404).json({ msg: '商品不存在' });
    Object.assign(product, {
      name, price, image, logo,
      images: Array.isArray(images) ? JSON.stringify(images) : images,
      stock, description, category_id, user_category_id
    });
    await product.save();
    res.json({ msg: '商品更新成功', product });
  } catch (err) {
    res.status(500).json({ msg: '商品更新失败', err });
  }
};

exports.remove = async (req, res) => {
  try {
    const { id } = req.params;
    const product = await Product.findByPk(id);
    if (!product) return res.status(404).json({ msg: '商品不存在' });
    await product.destroy();
    res.json({ msg: '商品删除成功' });
  } catch (err) {
    if (err.name === 'SequelizeForeignKeyConstraintError') {
      return res.status(400).json({ msg: '该商品有关联订单，无法删除' });
    }
    res.status(500).json({ msg: '商品删除失败', err });
  }
};
